package com.ai.sys.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ai.tool.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;

/**
 * @ClassName: AbstractHttpDataHandler
 * @Description: 抽象数据处理
 * @author yanghao
 * @date 2015年2月2日 上午11:04:17
 *
 */
public abstract class AbstractHandler implements HttpHandler {

	/**
	 * @Title: getAttPram
	 * @Description: 获得请求参数
	 * @param @param httpExchange
	 * @param @param key
	 * @param @return 设定文件
	 * @return String 返回类型
	 * @throws
	 */
	protected String getAttPram(HttpExchange httpExchange, String key) {
		try {
			Headers headers = httpExchange.getRequestHeaders();
			List<String> dt = headers.get(key);
			return String.valueOf(dt.get(0));
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * @Title: getReqFile
	 * @Description: 获得传输的文件
	 * @param @param httpExchange
	 * @param @return
	 * @param @throws IOException 设定文件
	 * @return byte[] 返回类型
	 * @throws
	 */
	protected byte[] getReqFile(HttpExchange httpExchange) throws IOException {
		Headers headers = httpExchange.getRequestHeaders();
		List<String> cl = headers.get("Content-Length");
		int contentLength = Integer.parseInt(cl.get(0));
		InputStream in = httpExchange.getRequestBody();
		byte[] buf = {};
		int size = 0;
		if (contentLength != 0) {
			buf = new byte[contentLength];
			while (size < contentLength) {
				int c = in.read();
				buf[size++] = (byte) c;
			}
		}
		return buf;
	}

	protected JSONObject getReqJson(HttpExchange httpExchange) throws IOException {
		byte[] bts = getReqFile(httpExchange);
		String str = new String(bts, "UTF-8");
		JSONObject j = JSONObject.parseObject(str);
		return j;
	}

	/**
	 * @Title: buildResult
	 * @Description: 构建响应信息
	 * @param @return 设定文件
	 * @return Map<String,String> 返回类型
	 * @throws
	 */
	protected Map<String, String> buildResult() {
		Map<String, String> res = new HashMap<String, String>();
		res.put("result", "401");
		res.put("message", "失败");
		return res;
	}

	/**
	 * @throws Exception
	 * @Title: sendResponse
	 * @Description: 发送响应信息
	 * @param @param httpExchange
	 * @param @param res 设定文件
	 * @return void 返回类型
	 * @throws
	 */
	protected void sendResponse(HttpExchange httpExchange, Map<String, String> res) throws IOException {
		OutputStream out = null;
		try {
			String json = JSON.toJSONString(res);
			httpExchange.sendResponseHeaders(200, json.getBytes("UTF-8").length);
			out = httpExchange.getResponseBody();
			out.write(json.getBytes("UTF-8"));
			out.flush();
		} catch (IOException e) {
			throw e;
		} finally {
			FileUtil.close(out);
		}
	}

}
